﻿using System;
using System.Net;
using System.Xml;
using Sherwood.Web;

namespace Sherwood.Content.SearchClient
{
    public abstract class SearchClientBase
    {
        public string SearchServiceUrl { get; private set; }

        protected SearchClientBase(string searchServiceUrl)
        {
            Uri tmp;
            if (!Uri.TryCreate(searchServiceUrl, UriKind.Absolute, out tmp) || !string.IsNullOrEmpty(tmp.Query))
                throw new ArgumentException(
                    "searchServiceUrl should be an absolute path pointing to the service. e.g. http://search.site.com/search.ashx",
                    "searchServiceUrl");

            SearchServiceUrl = searchServiceUrl;
        }

        public XmlReader CreateSearchResultXmlReader(string solrSearchQuery)
        {
            return CreateSearchResultXmlReader(new QueryParameterCollection(solrSearchQuery));
        }

        public XmlReader CreateSearchResultXmlReader(QueryParameterCollection queryParameters)
        {
            PrepareSearchRequest(queryParameters);

            var request = WebRequest.Create(SearchServiceUrl + queryParameters);
            var response = request.GetResponse();
            return XmlReader.Create(response.GetResponseStream());
        }

        public string GetPreparedSearchUrl(string solrSearchQuery)
        {
            return SearchServiceUrl + GetPreparedSearchQueryString(solrSearchQuery);
        }

        public string GetPreparedSearchQueryString(string solrSearchQuery)
        {
            var queryParameters = new QueryParameterCollection(solrSearchQuery);
            PrepareSearchRequest(queryParameters);
            return queryParameters.ToString();
        }

        public abstract void PrepareSearchRequest(QueryParameterCollection queryParameters);
    }
}